#include <iostream>
#include <string>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>
using namespace std;

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void http_callback(wsserver_t *srv,websocketpp::connection_hdl hd1)
{
    wsserver_t::connection_ptr conn = srv->get_con_from_hdl(hd1);
    cout << "body:" << conn->get_request_body() << endl;
    websocketpp::http::parser::request req = conn->get_request();
    cout << "method:" << req.get_method() << endl;
    cout << "uri: " << req.get_uri() << endl;

    string body = "<html><body><h1>hello world</h1></body></html>";
    conn->set_body(conn->get_request_body());
    conn->append_header("Content-Type","text/html");
    conn->set_status(websocketpp::http::status_code::ok);
}

void wsopen_callback(wsserver_t *srv,websocketpp::connection_hdl hd1)
{
    cout << "握手成功" << endl;
}

void wsclose_callback(wsserver_t *srv,websocketpp::connection_hdl hd1)
{
    cout << "连接断开" << endl;
}

void wsmsg_callback(wsserver_t *srv,websocketpp::connection_hdl hd1,wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr conn = srv->get_con_from_hdl(hd1);
    cout << "messge:" << msg->get_payload() << endl;
    string rsp = "client say:" + msg->get_payload();
    conn->send(rsp);
}

int main()
{
    //1.实例化server对象
    wsserver_t wsser;
    //2.设置日志等级
    wsser.set_access_channels(websocketpp::log::alevel::none);
    //3.初始化asio调度器
    wsser.init_asio();
    wsser.set_reuse_addr(true);
    //4.设置回调参数
    wsser.set_http_handler(bind(http_callback,&wsser,placeholders::_1));
    wsser.set_open_handler(bind(wsopen_callback,&wsser,placeholders::_1));
    wsser.set_close_handler(bind(wsclose_callback,&wsser,placeholders::_1));
    wsser.set_message_handler(bind(wsmsg_callback,&wsser,placeholders::_1,placeholders::_2));
    //5.设置监听端口
    wsser.listen(8080);
    //6.开始获取新连接
    wsser.start_accept();
    //7.启动服务器
    wsser.run();
    return 0;
}



